package com.aiwei.tdjk.controller.sys;


import com.aiwei.tdjk.bean.annotation.Log;
import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.controller.BaseController;
import com.aiwei.tdjk.dto.request.GetUserPagerRequest;
import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.entity.UserOrganizationJob;
import com.aiwei.tdjk.enums.BooleanEnum;
import com.aiwei.tdjk.enums.UserStatusEnum;
import com.aiwei.tdjk.service.PasswordService;
import com.aiwei.tdjk.service.UserOrganizationJobService;
import com.aiwei.tdjk.service.UserService;
import com.aiwei.tdjk.utils.UserUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;

/**
 * <p>Version: 1.0
 */
@Controller("adminUserController")
@RequestMapping(value = "/admin/sys/user")
public class UserController extends BaseController<User> {

    @Autowired
    private UserService userService;
    @Autowired
    private UserOrganizationJobService userOrganizationJobService;

    @Autowired
    private PasswordService passwordService;


    private static Logger logger = Logger.getLogger(UserController.class);

    protected void setCommonData(Model model) {
        model.addAttribute("statusList", UserStatusEnum.values());
        model.addAttribute("booleanList", BooleanEnum.values());
    }

    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String main(Model model) {
        return viewName("main");
    }

    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public String tree(Model model) {
        return viewName("tree");
    }

    @Log(operationType="add操作:",operationName="添加用户")
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public String list(GetUserPagerRequest request, Model model) {
        logger.info("----------------user--------------------------");
        setCommonData(model);
        model.addAttribute("page", userService.find(request));
        model.addAttribute("user", request);
        return viewName("list");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") Long id) {

        setCommonData(model);
        model.addAttribute("m", userService.get(id));
        model.addAttribute(Constants.OP_NAME, "查看");
        model.addAttribute("displayOrganizationJobs", userOrganizationJobService.getByUserId(id));
        return viewName("editForm");
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "新增");
        if (!model.containsAttribute("m")) {
            User user = new User();
            user.setAdmin(false);
            user.setStatus(UserStatusEnum.normal.getCode().byteValue());
            model.addAttribute("m", user);
        }
        return viewName("editForm");
    }

    @Log(operationType="add操作:",operationName="添加用户")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(
            Model model, @Valid @ModelAttribute("m") User m, BindingResult result,
            @RequestParam(value = "organizationId", required = false) Long[] organizationIds,
            @RequestParam(value = "jobId", required = false) Long[][] jobIds,
            @RequestParam(value = "domicileId", required = false) Long[][]domicileIds,
            RedirectAttributes redirectAttributes) {


        if (hasError(result)) {
            return showCreateForm(model);
        }
        userService.save(m);
        //新增组织架构信息
        fillUserOrganization(m, organizationIds, jobIds);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
        return redirectToUrl("list");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "修改");
        model.addAttribute("m", userService.get(id));
        model.addAttribute("displayOrganizationJobs", userOrganizationJobService.getByUserId(id));
        return viewName("editForm");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update(
            Model model, @Valid @ModelAttribute("m") User m, BindingResult result,
            @RequestParam(value = "organizationId", required = false) Long[] organizationIds,
            @RequestParam(value = "jobId", required = false) Long[][] jobIds,
            @RequestParam(value = "domicileId", required = false) Long[][]domicileIds,
            RedirectAttributes redirectAttributes) {

        if (hasError(result)) {
            return showUpdateForm(m.getId(), model);
        }
        //修改基本信息
        userService.update(m);
        Long userId = m.getId();
        //修改组织机构信息
        userOrganizationJobService.deleteByUserId(userId);
        fillUserOrganization(m, organizationIds, jobIds);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
        return redirectToUrl("list");
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {

        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "删除");
        model.addAttribute("m", userService.get(id));
        model.addAttribute("displayOrganizationJobs", userOrganizationJobService.getByUserId(id));
        return viewName("editForm");
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    public String delete(
            @PathVariable("id") Long id,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        userService.delete(id);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("list");
    }

    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteInBatch(
            @RequestParam(value = "ids", required = false) Long[] ids,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        userService.delete(ids);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("list");
    }


    private void fillUserOrganization(User m, Long[] organizationIds, Long[][] jobIds) {
        if (ArrayUtils.isEmpty(organizationIds)) {
            return;
        }
        for (int i = 0, l = organizationIds.length; i < l; i++) {

            //仅新增/修改一个 spring会自动split（“，”）--->给数组
            if (l == 1) {
                for (int j = 0, l2 = jobIds.length; j < l2; j++) {
                    UserOrganizationJob userOrganizationJob = new UserOrganizationJob();
                    userOrganizationJob.setOrganizationId(organizationIds[i]);
                    userOrganizationJob.setJobId(jobIds[j][0]);
                    userOrganizationJob.setUserId(m.getId());
                    userOrganizationJobService.add(userOrganizationJob);
                }
            } else {
                Long[] jobId = jobIds[i];
                for (int j = 0, l2 = jobId.length; j < l2; j++) {
                    UserOrganizationJob userOrganizationJob = new UserOrganizationJob();
                    userOrganizationJob.setOrganizationId(organizationIds[i]);
                    userOrganizationJob.setJobId(jobId[j]);
                    userOrganizationJob.setUserId(m.getId());
                    userOrganizationJobService.add(userOrganizationJob);
                }
            }

        }
    }


    /**
     * 修改密码
     * @param request
     * @param ids
     * @param newPassword
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "changePassword")
    public String changePassword(
            HttpServletRequest request,
            @RequestParam("ids") Long[] ids, @RequestParam("newPassword") String newPassword,
            RedirectAttributes redirectAttributes) {

        userService.changePassword(ids, newPassword);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "改密成功！");

        return redirectToUrl("list");
    }

    /**
     * 修改状态
     * @param request
     * @param ids
     * @param newStatus
     * @param reason
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "changeStatus/{newStatus}")
    public String changeStatus(
            HttpServletRequest request,
            @RequestParam("ids") Long[] ids,
            @PathVariable("newStatus") UserStatusEnum newStatus,
            @RequestParam("reason") String reason,
            RedirectAttributes redirectAttributes) {

        userService.changeStatus(ids, newStatus, reason);

        if (newStatus == UserStatusEnum.normal) {
            redirectAttributes.addFlashAttribute(Constants.MESSAGE, "解封成功！");
        } else if (newStatus == UserStatusEnum.blocked) {
            redirectAttributes.addFlashAttribute(Constants.MESSAGE, "封禁成功！");
        }

        return redirectToUrl("list");
    }

    /**
     * 还原删除的用户
     * @param request
     * @param ids
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "recycle")
    public String recycle(HttpServletRequest request, @RequestParam("ids") Long[] ids, RedirectAttributes redirectAttributes) {
        for (Long id : ids) {
            User user = userService.get(id);
            user.setDeleted(Boolean.FALSE);
            userService.update(user);
        }
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "还原成功！");
        return redirectToUrl("list");
    }


    /**
     * sys/editForm 表单验证
     * @param username
     * @param email
     * @param mobilePhoneNumber
     * @return
     */
    @RequestMapping(value = "validate")
    @ResponseBody
    public Object validate(String username,String email,String mobilePhoneNumber,Long id,String employeeId){
        Object uSure=userService.findByUsername(username,id);
        Object eSure=userService.findByMobilePhoneNumber(mobilePhoneNumber,id);
        Object mSure=userService.findByEmail(email,id);
        Object pSure=userService.findEmployeeId(employeeId,id);
        if (uSure!=null) {
            return "error";
        } else if (eSure!=null){
            return "error";
        }else if(mSure!=null){
            return "error";
        } else if(pSure!=null){
            return "error";
        }
        return "pass";
    }

    @RequestMapping("ajax/autocomplete")
    @ResponseBody
    public Set<Map<String, Object>> autocomplete(
            @RequestParam("term") String term) {

        return userService.findIdAndNames(term);
    }

    @RequestMapping("autocomplete")
    public String autocomplete() {
        return viewName("autocomplete");
    }
    /**
     * 跳到修改密码的界面
     * @return
     */
    @RequestMapping(value = "updatePassword",method = RequestMethod.GET)
    public String editPwd(Model model){
        model.addAttribute("user", UserUtil.getUserFromSession());
        return viewName("updatePassword");
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "updatePassword",method = RequestMethod.POST)
    public String editFowd(User user,RedirectAttributes redirectAttributes){
        User user2=userService.get(user.getId());
        user.setPassword(passwordService.encryptPassword(user2.getUsername(), user.getPassword(), user2.getSalt()));
        int row=userService.update(user);
        if(row>0) {
            redirectAttributes.addFlashAttribute("message", "修改成功！下次登录记得使用新密码哦！");
            return redirectToUrl("updatePassword");
        }
        else{
            redirectAttributes.addFlashAttribute("message", "修改失败");
            return redirectToUrl("updatePassword");
        }
    }

    /**
     * 判断是否和登录的用户密码一致
     * @return
     */
    @RequestMapping("inspectPwd")
    @ResponseBody
    public Boolean inspectPwd(String oldPassword,long userId){
        User user=userService.get(userId);
        if(passwordService.encryptPassword(user.getUsername(), oldPassword, user.getSalt()).equals(user.getPassword())){
            return true;
        }
        else{
            return false;
        }

    }

    /**
     * 查询用户信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("{id}/userById")
    public String findById(@PathVariable long id,Model model){
        model.addAttribute("displayOrganizationJobs", userOrganizationJobService.getByUserId(id));
        model.addAttribute("user",userService.get(id));
        return viewName("findUserById");
    }

    /**
     * 跳转到头像上传页面
     * @param model
     * @return
     */
    @RequestMapping(value = "uploadIcon",method = RequestMethod.GET)
    public String uploadIcon(Model model){
        User user = UserUtil.getUserFromSession();
        model.addAttribute("user",userService.get(user.getId()));
        return viewName("uploadIcon");
    }


}
